package com.promise.jokerdream.work.signup

import com.promise.jokerdream.work.BaseWork
import com.promise.jokerdream.work.WorkResult
import com.promise.jokerdream.repository.GameApi
import com.promise.jokerdream.repository.foldWithApiException
import com.promise.jokerdream.manager.ExecutionHistoryManager
import com.promise.jokerdream.utils.AppContext
import java.util.Calendar

// 群雄逐鹿工作
class ThronesBattleWork(override val uin: String): BaseWork(uin) {
    
    private val gameApi = GameApi.Companion.getInstance()
    private val historyManager by lazy { ExecutionHistoryManager.Companion.getInstance(AppContext.get()) }
    
    override val name: String = "群雄逐鹿"
    
    override suspend fun executeWork(): WorkResult {
        try {
            // 1. 查询群雄逐鹿状态
            val queryResult = gameApi.queryThronesBattle()
            
            queryResult.foldWithApiException(
                onSuccess = { response ->
                    // 2. 检查是否需要报名：isSignUpTime=1且signedUpCamp=0
                    if (response.isSignUpTime == 1 && response.signedUpCamp == 0) {
                        val signupResult = gameApi.signupThronesBattle()
                        signupResult.foldWithApiException(
                            onSuccess = { signupResponse ->
                                historyManager.addHistory(name, signupResponse.getDescription())
                            },
                            onFailure = { code, msg ->
                                historyManager.addHistory(name, msg, code)
                            }
                        )
                    }
                    
                    // 3. 领奖
                    val claimRewardResult = gameApi.claimThronesBattleReward()
                    claimRewardResult.foldWithApiException(
                        onSuccess = { claimResponse ->
                            historyManager.addHistory(name, claimResponse.getDescription())
                        },
                        onFailure = { code, msg ->
                            // 未报名
                            if (code != -1006 && code != -10011 && code != -10014) {
                                historyManager.addHistory(name, msg, code)
                            }
                        }
                    )
                    
                    // 4. 领排名奖（周三14:00之后到周日都可以领取）
                    if (canClaimRankReward()) {
                        val claimRankRewardResult = gameApi.claimThronesBattleRankReward()
                        claimRankRewardResult.foldWithApiException(
                            onSuccess = { rankRewardResponse ->
                                historyManager.addHistory(name, rankRewardResponse.getDescription())
                            },
                            onFailure = { code, msg ->
                                if (code != -1009 && code != -1010) { // 没有排名奖可领
                                    historyManager.addHistory(name, msg, code)
                                }
                            }
                        )
                    }
                },
                onFailure = { code, msg ->
                    historyManager.addHistory(name, msg, code)
                    return WorkResult.Failure(Exception(msg), msg)
                }
            )
            
            return WorkResult.Success
        } catch (e: Exception) {
            historyManager.addHistory(name, e.message)
            return WorkResult.Failure(e, e.message)
        }
    }
    
    /**
     * 检查当前时间是否可以领排名奖
     * 周三14:00之后到周日都可以领排名奖
     * @return 是否可以领排名奖
     */
    private fun canClaimRankReward(): Boolean {
        val calendar = Calendar.getInstance()
        val dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK)
        val hour = calendar.get(Calendar.HOUR_OF_DAY)
        
        // 周三14:00之后到周日都可以领排名奖
        when (dayOfWeek) {
            Calendar.WEDNESDAY -> {
                // 周三需要14:00之后
                return hour >= 14
            }
            Calendar.THURSDAY, Calendar.FRIDAY, Calendar.SATURDAY, Calendar.SUNDAY -> {
                // 周四到周日全天都可以
                return true
            }
            else -> {
                // 周一周二不能领
                return false
            }
        }
    }
}